package cn.edu.tyu.finance.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.tyu.finance.domain.Category;
import cn.edu.tyu.finance.util.DbUtil;

/**
 * 查询类别的Servlet
 * @author duhaohao
 * @version 1.0
 */
@WebServlet("/FindThingsServlet")
public class FindThingsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindThingsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//连接数据库，从数据库里查询所有类别，跳转到JSP网页上显示数据
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<Category> categoryList = new ArrayList<Category>();
		
		conn = DbUtil.getConnection();
		String sql = "SELECT id,name,remark FROM category";
		try {
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				Category ct = new Category();
				ct.setId(rs.getString("id"));
				ct.setName(rs.getString("name"));
				ct.setRemark(rs.getString("remark"));
				categoryList.add(ct);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.backConn(conn, pstmt, rs);
		}
		//把集合保存到session中，在JSP网页上提取session中数据
		request.getSession().setAttribute("clist", categoryList);
		//跳转网页，在网页上显示数据
		response.sendRedirect("displayThings.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}